<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
    public $layout='//layouts/dummy';
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public $categories;
	public $pages;

	public function actionLang()
	{
		$lang = isset($_POST['boxanh_lang']) ? $_POST['boxanh_lang'] : "en";
		Yii::app()->session['boxanh_lang'] = $lang;
	}

	public function actionIndex()
	{
		// $criteria = new CDbCriteria();
        // $criteria->select = 'id, name';
        // $criteria->condition = 'status = :status';
        // $criteria->params = array(':status'=> 1);
        // $this->categories = Category::model()->findAll($criteria);

        // $id = isset($_GET["id"]) ? $_GET["id"] : $this->categories[0]->id;
		/////////////////product/////////////////////////
        $criteria = new CDbCriteria();
        $criteria->select = 'id, name, on_sale, image';
        // $criteria->condition = 'category_id = :id';
		$criteria->limit = 8;
		$criteria->offset = 0;
        $criteria->order = 'on_sale ASC';
        // $criteria->params = array(':id'=> $id);

        $count= Product::model()->count($criteria);
        $this->pages= new CPagination($count);
        $this->pages->pageSize = 8;
        $this->pages->applyLimit($criteria);

        $products = Product::model()->findAll($criteria);
		///////////////end product/////////////////////////
        $this->layout = "MasterLayout";
		$this->render("home",array("products" => $products));

	}
/*
	public function checkInitDatabase()
	{
		yii::trace("checkInitDatabase", "dnd.all");

		$config = Config::model()->findByPk("init");
		if($config===null)
		{
			throw new CHttpException(504,'Internal server error');
		}
		else
		{
			if ($config->value === '0')
			{
				return true;
			}
			return false;	
		}	
	}
	public function initDatabase()
	{
		yii::trace("InitDatabase", "dnd.all");

		$connection = Yii::app()->db;
		$transaction=$connection->beginTransaction();

		try
		{
			
			$connection->createCommand("drop table if exists dnd_boxanhfood_authassignment")->execute();
			$connection->createCommand("drop table if exists dnd_boxanhfood_authitemchild")->execute();
			$connection->createCommand("drop table if exists dnd_boxanhfood_authitem")->execute();
			$connection->createCommand("delete from dnd_boxanhfood_administator")->execute();

			$command = $connection->createCommand();
			$command->createTable('dnd_boxanhfood_authitem', array(
   					'name' =>'varchar(64) NOT NULL',
   					'type' =>'integer NOT NULL',
   					'description' =>'text',
   					'bizrule' =>'text',
   					'data' =>'text',
   					'PRIMARY KEY (`name`)',
   			), 'ENGINE=InnoDB');

			$command->createTable('dnd_boxanhfood_authitemchild', array(
   					'parent' =>'varchar(64) NOT NULL',
   					'child' =>'varchar(64) NOT NULL',
   					'PRIMARY KEY (`parent`,`child`)',
   			), 'ENGINE=InnoDB');

   			$command->addForeignKey("fk_auth_item_child_parent", "dnd_boxanhfood_authitemchild", "parent", "dnd_boxanhfood_authitem", "name", "CASCADE", "CASCADE");
   			$command->addForeignKey("fk_auth_item_child_child", "dnd_boxanhfood_authitemchild", "child", "dnd_boxanhfood_authitem", "name", "CASCADE", "CASCADE");	
			
			$command->createTable('dnd_boxanhfood_authassignment', array(
   					'itemname' =>'varchar(64) NOT NULL',
   					'userid' =>'int(11) NOT NULL',
   					'bizrule' =>'text',
   					'data' =>'text',
   					'PRIMARY KEY (`itemname`,`userid`)',
   			), 'ENGINE=InnoDB');

   			$command->addForeignKey(
			   "fk_auth_assignment_itemname",
			   "dnd_boxanhfood_authassignment",
			   "itemname",
			   "dnd_boxanhfood_authitem",
			   "name",
			   "CASCADE",
			   "CASCADE"
			);

   			$command->addForeignKey(
			   "fk_auth_assignment_userid",
			   "dnd_boxanhfood_authassignment",
			   "userid",
			   "dnd_boxanhfood_administator",
			   "id",
			   "CASCADE",
			   "CASCADE"
			);
			

			$auth = Yii::app()->authManager;
			$adminRole = $auth->createRole(AdministatorController::ROLE_ADMINISTATOR);
			$superAdminRole = $auth->createRole(AdministatorController::ROLE_SUPER_ADMINISTATOR);
			$superAdminRole->addChild(AdministatorController::ROLE_ADMINISTATOR);

			
   			$admin = new Administator;
			$admin->attributes = array('username' => 'admin', 'password' => '123456' , "password_repeat" => '123456');

			if (!$admin->save())
			{
				 throw new Exception('Failed to create admin.');
			}
			
			$adminId = $admin->primaryKey;
			$auth->assign(AdministatorController::ROLE_SUPER_ADMINISTATOR, $adminId);
			$transaction->commit();

			$config = Config::model()->findByPk("init");
			if($config===null)
			{

			}
			else
			{
				$config->value = "1";
				$config->save();
			}
			yii::trace("InitDatabase - commit", "dnd.all");
		}
		catch(Exception $e)
		{
   			$transaction->rollback();
   			$this->renderText($e->getMessage());
		}
	}
*/
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-Type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
        
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
            $model->validate();
            $model->login();
			if($model->validate() && $model->login())
            {
               $this->redirect(array('admin/orderAdmin/index'));
            }
				
		}
		// display the login form
        $this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(array('site/login'));
	}
}